<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2021-12-01 09:56:56
 * @LastEditors: Sam
 * @LastEditTime: 2022-01-22 20:31:33
 */


namespace app\develop\controller;


use think\facade\Db;
use Generate;

class Validator extends Base
{
    /**
     * 类型对应的规则
     * @var string[]
     */
    protected $type_rules = [
        'tinyint'   => 'integer',
        'smallint'  => 'integer',
        'mediumint' => 'integer',
        'int'       => 'integer',
        'integer'   => 'integer',
        'bigint'    => 'integer',
        'float'     => 'float',
        'double'    => 'float',
        'decimal'   => 'number',
        'unsigned'  => '>=:0',
//        'varchar'    => '',
//        'char'       => '',
//        'tinytext'   => '',
//        'text'       => '',
//        'mediumtext' => '',
//        'longtext'   => '',
        'date'      => 'date',
    ];

    public function index()
    {
        $dbtables = Db::query("SELECT TABLE_NAME Name FROM information_schema.tables WHERE TABLE_NAME LIKE '%".config('database.prefix')."_%'");

        $this->assign('tables', $dbtables);
        if (request()->param('table')) {
            $table     = request()->param('table');
            $prefix    = app()->env->get(SYSTEM . 'db_pre');
            $tableInfo = Db::query('SHOW FULL FIELDS FROM ' . $table);
            $info      = [];
            foreach ($tableInfo as $value) {
                $rule  = [];
                $rule2 = [];
                $this->getRule($rule, $rule2, $value['Type']);
                if ($value['Null'] == 'NO') $rule[] = 'require';
                $info[] = [
                    'field'   => $value['Field'],
                    'rule'    => $rule,
                    'rule2'   => $rule2,
                    'comment' => $value['Comment']
                ];
            }
            $this->assign('table_info', json_encode($info));
        } else {
            $this->assign('table_info', json_encode([]));
        }
        return $this->fetch();
    }

    /**
     * 生成验证器
     */
    public function run()
    {
        $generate = new Generate();
        $data     = request()->post();
        try{
            $result = $generate->run($data, request()->post('file'));
        }catch(\Exception $e){
            json_response(0,$e->getMessage());
        }

        json_response(1,'创建成功');
    }

    protected function getRule(&$rule, &$rule2, $type)
    {
        $rule = [];
        $type = str_replace(['(', ')', ' '], [',', '', ','], $type);
        $type = explode(',', $type);
        foreach ($type as $value) {
            if (key_exists($value, $this->type_rules)) {
                $rule[] = $this->type_rules[$value];
            } else if (intval($value) > 0) {
                $rule2 = 'length:' . $value;
            }
        }
    }


}